package com.example.test06thread.collectionThread;

import org.junit.Test;

import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Collectors;

/**
 * @Author: fxy
 * @Date: 2022/05/25/11:23
 * @Description:
 */
public class ListTest {

    //ArrayList不安全
    public static void main(String[] args) {
        ListTest test = new ListTest();
        //test.copyOnWriteArrayListTest();
        test.synchronizedListTest();
    }

    public void arrayListTest(){
        ArrayList<String> list = new ArrayList<>();
        for (int i=0;i<=100;i++){
            new Thread(()->{
                list.add(UUID.randomUUID().toString().substring(0,5));
                System.out.println(list);
            },String.valueOf(i)).start();
        }
    }
    public void vectorTest(){
        List<String> list = new Vector<>();
        for (int i=0;i<=100;i++){
            new Thread(()->{
                list.add(UUID.randomUUID().toString().substring(0,5));
                System.out.println(list);
            },String.valueOf(i)).start();
        }
    }

    public void copyOnWriteArrayListTest(){
        List<String> list = new CopyOnWriteArrayList<>();
        for (int i=0;i<=100;i++){
            new Thread(()->{
                list.add(UUID.randomUUID().toString().substring(0,5));
                System.out.println(list);
            },String.valueOf(i)).start();
        }
    }

    public void synchronizedListTest(){
        List<String> list = Collections.synchronizedList(new ArrayList<>());
        for (int i=0;i<=100;i++){
            new Thread(()->{
                list.add(UUID.randomUUID().toString().substring(0,5));
                System.out.println(list);
            },String.valueOf(i)).start();
        }
    }
}
